<?php
require "./vendor/autoload.php";

use PhpAmqpLib\Connection\AMQPStreamConnection;

use PhpAmqpLib\Message\AMQPMessage;

//声明连接参数
$conf = [
    'host' => PHP_OS == "Linux" ? '127.0.0.1' : '10.0.0.200',
    'vhost' => '/', //类比数据库名称
    'port' => 5672,
    'user' => 'wyqgg',
    'pwd' => '123456',
];
//连接broker

$exchangeName = 'kd_sms_send_ex'; //交换机名

$queueName = 'kd_sms_send_q'; //队列名称

$routingKey = 'sms_send'; //路由关键字(也可以省略)

$conn = new AMQPStreamConnection( //建立生产者与mq之间的连接

    $conf['host'], $conf['port'], $conf['user'], $conf['pwd'], $conf['vhost']

);


if (!$conn) {
    echo "连接失败";
    exit();
}

//创建信道
$ch = $conn->channel();

//成功调用
$ch->set_ack_handler(function (AMQPMessage $msg) {
    echo "发送消息{$msg->body}成功!" . PHP_EOL;
});
//失败调用
$ch->set_nack_handler(function (AMQPMessage $msg) {
    echo "发送消息{$msg->body}失败!" . PHP_EOL;
});
//开启confirm机制
$ch->confirm_select();
//交换机
$ch->exchange_declare($exchangeName, \PhpAmqpLib\Exchange\AMQPExchangeType::DIRECT, false, true, false);
//队列
$ch->queue_declare($queueName, false, true, false, false);
//绑定交换机和队列
$ch->queue_bind($queueName, $exchangeName, $routingKey);
//发送消息
for ($i = 0; $i < 10; $i++) {
    $body = time() . $i . PHP_EOL;
    $msg = new AMQPMessage($body, ['content_type' => 'text/plain', 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT]);
    $ch->basic_publish($msg, $exchangeName, $routingKey);
    $ch->wait_for_pending_acks_returns(1); //必须开启
    echo "发送消息:" . $i . "\n";
    sleep(1);
}


$ch->close();
$conn->close();